import java.util.InputMismatchException;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);


        Boolean flag = true;
        int num1=0,i=0;

        while (true) {
            if (flag) {
                num1 = (int) (Math.random() * 100 + 1);
                i = 7;//游戏次数
                System.out.println("这是一个猜数字游戏,输入与系统随机生成数字一样则游戏胜利,您共有" + i + "次机会" + "\n请输入[1，100]的数字:");
            }
            while (flag) {
                try {
                    int num2 = scanner.nextInt();

                    if (num2 > num1) {
                        System.out.println("您猜测的数字大了！");
                    } else if (num2 < num1) {
                        System.out.println("您猜测的数字小了！");
                    } else {
                        System.out.println("您猜测的数字正确，游戏胜利！");
                        break;
                    }

                    i--;
                    if (i == 0) {
                        System.out.println("机会耗尽，游戏失败！");
                        break;
                    } else {
                        System.out.println("您还有" + i + "次机会");
                    }
                }catch (InputMismatchException input){
                    i--;
                    System.out.println("输入并非数字，但机会依旧减一");
                    scanner.nextLine();
                    if (i==0){
                        System.out.println("机会耗尽，游戏失败！");
                        break;
                    }else {
                        System.out.println("您还有" + i + "次机会");
                    }
                }
            }
            System.out.println("是否开始下一局游戏? Y/N");
            String string = scanner.next();
            if (string.equalsIgnoreCase("n")){
                System.out.println("游戏结束！");
                break;
            }else  if (string.equalsIgnoreCase("y")){
                flag = true;
                System.out.println("开启下一局,游戏继续----------------------------------------------------------------------------------------------------------------------");
            }else {
                System.out.println("\n输入非法，请重新输入！");
                flag = false;
            }

        }
    }
}
